﻿using System;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using iTunesLib;
using Twitterizer;

namespace Twittscrobbler
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        extern static int RegisterHotKey(IntPtr HWnd, int ID, int MOD_KEY, int KEY);
        [DllImport("user32.dll")]
        extern static int UnregisterHotKey(IntPtr HWnd, int ID);
        const int MOD_ALT = 0x0001;
        const int MOD_CONTROL = 0x0002;
        const int MOD_SHIFT = 0x0004;
        const int WM_HOTKEY = 0x0312;
        const int HOTKEY_CONTROL_SHIFT = 0x0001;

        //iTunes管理用、認証用、StatusUpdate用、PIN要求用、ログインフラグ
        private iTunes_scrobble itunes_s;
        private OAuthTokens tokens;
        private UpdateProfileOptions profiles;
        private OAuthTokenResponse oatr;
        private TwitterUser profiles2;
        private Boolean login_flug;
        AESuru aesuru;

        //クライアントキー、アクセストークン、表示名、ID(DECIMAL)保持用
        static string ConsumerKey = "py3LNTbEnh6mBnnZMbg";
        static string ConsumerSecret = "qDQzL1vlwyYlurqDbpHKTK4d0Y6ddnqG9jqSj910";
        static string AccessToken = "";
        static string AccessTokenSecret = "";
        private decimal uid;



        private void init()
        {
            toolStripStatusLabel1.Text = "初期化中です";
            toolStripStatusLabel2.Text = "140";

            //Oauth管理、StatusUpdate用
            tokens = new OAuthTokens();
            profiles = new UpdateProfileOptions();
            profiles2 = new TwitterUser();
            aesuru = new AESuru();

            //コンシューマキー収納
            tokens.ConsumerKey = ConsumerKey;
            tokens.ConsumerSecret = ConsumerSecret;

            toolStripStatusLabel1.Text = "iTunes初期化";

            //iTunes起動、監視
            object objform = this;
            itunes_s = new iTunes_scrobble(objform);

            //グローバルホック登録
            RegisterHotKey(this.Handle, HOTKEY_CONTROL_SHIFT, MOD_SHIFT | MOD_CONTROL, 0);

            toolStripStatusLabel1.Text = "初期化完了";


            //アクセストークンファイルの自動/手動取得
            if (File.Exists("./_twittscrobbler") == true)
                get_Token_File();
            else
            {
                get_Token();
            }

        }


        private void get_Token_File()
        {

            toolStripStatusLabel1.Text = "認証情報を復号化中…";
            string token = aesuru.Decrypt("_twittscrobbler");
            toolStripStatusLabel1.Text = "認証情報を復号しました。";
            tokens.AccessToken = AccessToken = token.Split('\n')[0];
            tokens.AccessTokenSecret = AccessTokenSecret = token.Split('\n')[1];
            uid = int.Parse(token.Split('\n')[2]);


            //ユーザープロフィール形成
            TwitterResponse<TwitterUser> user = TwitterUser.Show(tokens, uid);
            if (user.Result == RequestResult.Success)
            {
                name_ = user.ResponseObject.Name;
                profiles.Name = user.ResponseObject.Name;
                profiles.Location = user.ResponseObject.Location;
                profiles.Description = user.ResponseObject.Description;
                profiles.Url = user.ResponseObject.Website;
            }

            toolStripStatusLabel1.Text = "認証成功";


            label1.Text = name_;
            itunes_s.itunes_OnPlayerPlayEvent(null);
            //Flug
            login_flug = true;
        }
        private void get_Token()
        {
            toolStripStatusLabel1.Text = "PIN取得用URL発行中";

            //PIN取得
            oatr = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, "oob");
            Uri uri = Twitterizer.OAuthUtility.BuildAuthorizationUri(oatr.Token);
            System.Diagnostics.Process.Start(uri.ToString());


            label1.Text = "　　　　　　　　　 Input PIN";
            itunes_s.itunes_OnPlayerPlayEvent(null);
            textBoxPin.Visible = true;
            buttonRegisterPin.Visible = true;
            this.TopMost = true;
        }



        //イベントハンドラオーバライド
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_HOTKEY)
            {
                if ((int)m.WParam == HOTKEY_CONTROL_SHIFT)
                {
                    if (this.TopMost)
                    {
                        this.TopMost = false;
                        this.Text = "Twittscrobbler";
                    }
                    else
                    {
                        this.TopMost = true;
                        this.Text = "Twittscrobbler(Lock)";
                    }
                }
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            post();
        }


        private void post()
        {
            toolStripStatusLabel1.Text = "投稿中です";

            //名前長さ調整
            if (label1.Text.Length - 20 > 0)
                profiles.Name = label1.Text.Remove(20, label1.Text.Length - 20);
            else
                profiles.Name = label1.Text;
            //ユーザーステータス更新
            try
            {
                TwitterResponse<TwitterUser> tweetResponse = TwitterAccount.UpdateProfile(tokens, profiles);
            }
            catch
            {
                toolStripStatusLabel1.Text = "ステータス更新エラー\n" + toolStripStatusLabel1.Text;
            }
            //ツイート
            try
            {
                String postStr = textBoxTweetMsg.Text;
                if (postStr.Length > 140)
                {
                    DialogResult result = MessageBox.Show("140字を超えています．141字目以降は投稿されませんがよろしいですか？", "確認",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        postStr = postStr.Remove(140);
                    }
                    if (result == System.Windows.Forms.DialogResult.Cancel)
                    {
                        return;
                    }
                }
                TwitterResponse<TwitterStatus> tweetResponses = TwitterStatus.Update(tokens, postStr);
                toolStripStatusLabel1.Text = "投稿完了！";
                textBoxTweetMsg.Text = "";
            }
            catch
            {
                toolStripStatusLabel1.Text = "投稿失敗\n" + toolStripStatusLabel1.Text;
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            //ユーザートークン取得
            string pin = textBoxPin.Text;

            toolStripStatusLabel1.Text = "認証中…";

            //PINからアクセストークン取得
            OAuthTokenResponse res = OAuthUtility.GetAccessToken(
              ConsumerKey, ConsumerSecret, oatr.Token, pin);

            //トークン作成
            tokens.AccessToken = AccessToken = res.Token;
            tokens.AccessTokenSecret = AccessTokenSecret = res.TokenSecret;
            uid = res.UserId;

            toolStripStatusLabel1.Text = "認証成功";

            //ユーザープロフィール形成
            TwitterResponse<TwitterUser> user = TwitterUser.Show(tokens, uid);
            if (user.Result == RequestResult.Success)
            {
                name_ = user.ResponseObject.Name;
                profiles.Name = user.ResponseObject.Name;
                profiles.Location = user.ResponseObject.Location;
                profiles.Description = user.ResponseObject.Description;
                profiles.Url = user.ResponseObject.Website;
            }

            //Form形成
            label1.Text = name_;
            itunes_s.itunes_OnPlayerPlayEvent(null);
            textBoxPin.Visible = false;
            buttonRegisterPin.Visible = false;
            this.TopMost = false;

            //Flug
            login_flug = true;

            //アクセストークンの暗号化保存
            toolStripStatusLabel1.Text = "認証情報を暗号化中…";
            aesuru.Encrypt("_twittscrobbler",AccessToken + "\n" + AccessTokenSecret + "\n" + uid);
            toolStripStatusLabel1.Text = "暗号化が完了しました。";
        }

        public Form1()
        {
            InitializeComponent();
            init();
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            restoreName();

            if (itunes_s != null)
                itunes_s.unhock();
        }

        private void textBoxTweetMsg_TextChanged(object sender, EventArgs e)
        {
            int restCharacter = 140 - textBoxTweetMsg.Text.Length;
            if (restCharacter < 0)
            {
                toolStripStatusLabel2.ForeColor = Color.Red;
            }
            else
            {
                toolStripStatusLabel2.ForeColor = Color.Black;
            }
            toolStripStatusLabel2.Text = restCharacter.ToString();
        }

        private void textBoxTweetMsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (e.Control)
                {
                    post();
                }
            }
        }


        private void restoreName()
        {
            profiles.Name = name_;

            //ユーザーステータス更新
            TwitterResponse<TwitterUser> tweetResponse;
            if (login_flug)
            {

                try
                {
                    tweetResponse = TwitterAccount.UpdateProfile(tokens, profiles);
                }
                catch
                {
                    toolStripStatusLabel1.Text = "ステータス更新エラー\n" + toolStripStatusLabel1.Text;

                } 
            }
        }

    }
}
